import {ref} from 'vue';
import {defineStore} from 'pinia';
import store from '@/store';
import {resetRouter} from '@/router';
import {getUserInfoApi, userLogoutApi} from '@/api/login/index';

export const useUserStore = defineStore('user', () => {
    const username = ref<string>('');

    // 获取用户信息
    const getUserInfo = async () => {
        const {data: res} = await getUserInfoApi();
        if (res.code === 100000) {
            username.value = res.data.name;
        }
    };

    // 退出登录
    const userLogout = async () => {
        const {data: res} = await userLogoutApi();
        // 退出登录后跳转到uuap登录页面
        if (res.code === 40001) {
            // 重置路由
            resetRouter();
            console.log('退出成功');
        }
    };

    return {username, getUserInfo, userLogout};
});

/** 在 setup 外使用 */
export function useUserStoreHook() {
    return useUserStore(store);
}
